﻿using System;
using System.Linq;

namespace FranceTriple.Dal
{
    public class EventDal
    {
        public static EventCategory GetEventCategory(Int32 EventCategoryId)
        {
            EventCategory eventCategory;                    
            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    eventCategory = (from ev in ctx.EventCategorySet
                                     where (ev.Id == EventCategoryId)
                             select ev).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("RetrieveError".ToLocalizedString(), "EventCategory", ex.Message), ex) { EntityType = typeof(EventCategory) };
            }
            return eventCategory;
        }

        public static void UpdateEntity(Event entity)
        {
            try
            {
                using (FranceTriple.Dal.Model1Container ctx = new Model1Container())
                {
                    var eventToUpdate = ctx.EventSet.Where(ec => ec.Id == entity.Id).FirstOrDefault();
                    //Todo : vérifier que le composant ListView prend en compte le scénario suivant : 
                    // 1 utilisateur entre en édition, 1 autre suprrime la meme ligne, le premier sauvegarde sa modification
                    //if (eventToUpdate == null)
                    //{
                    //    CreateEntity(entity, null);
                    //    return;
                    //}

                    eventToUpdate.TitleEvent = entity.TitleEvent;
                    eventToUpdate.AuthorEvent = entity.AuthorEvent;
                    eventToUpdate.DateStartEvent = entity.DateStartEvent;
                    eventToUpdate.DateEndEvent = entity.DateEndEvent;
                    eventToUpdate.AllDayEvent = entity.AllDayEvent;
                    eventToUpdate.DescriptionEvent = entity.DescriptionEvent;

                    eventToUpdate.EventCategory = (EventCategory)ctx.GetObjectByKey(entity.EventCategory.EntityKey); 

                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message);
                throw new DalException(String.Format("UpdateError".ToLocalizedString(), "Event", ex.Message), ex) { EntityType = typeof(Event) };
            }
        }
    }
}
